package org.jeecg.modules.webSocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;

@Component
@Slf4j
@ServerEndpoint("/") // 前端 ws://localhost:9096/ 即可连接
public class JeecgWebSocket {

    /** 保存所有连接的 session */
    private static final Set<Session> sessions = ConcurrentHashMap.newKeySet();

    /** 定时任务线程池（单线程即可） */
    private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    /** 静态代码块：项目启动时即开始定时推送 */
    static {
//        log.info("✅ WebSocket 定时推送任务初始化...");
//        scheduler.scheduleAtFixedRate(() -> {
//
//        }, 0, 2, TimeUnit.SECONDS);
    }

    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        try {
            log.info(getAddr(session) + "," + session.getId() + "," + "连接成功");
            session.getBasicRemote().sendText("连接成功!");
        } catch (IOException e) {
            log.error("连接成功消息发送失败", e);
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            // 如果收到的是上位机的消息，则转发给前端
            if(getAddr(session).equals("up")){
                log.info("上位机发来消息,id:" + session.getId());
                log.info(message);
                sendMsgToFront(message);
            }
            if(getAddr(session).equals("front")){
                log.info("下位机发来消息,id:" + session.getId());
                log.info(message);
                sendMsgToUp(message);
            }
            session.getBasicRemote().sendText("服务器已收到: " + message);
        } catch (Exception e) {
            log.error("消息回复失败", e);
        }
    }

    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        log.info("前端已断开: {}", session.getId());
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("WebSocket错误: {}", error.getMessage());
    }

    // 向网页端发送消息
    public void sendMsgToFront(String msg){
        for (Session session : sessions) {
            if (session.isOpen() && getAddr(session).equals("front")) {
                try {
//                    String msg = "服务器定时推送: " + System.currentTimeMillis();
                    session.getBasicRemote().sendText(msg);
                    log.info("已推送消息给客户端: {}", session.getId());
                } catch (IOException e) {
                    log.error("推送失败: {}", e.getMessage());
                }
            }
        }
    }
    public void sendMsgToUp(String msg){
        for (Session session : sessions) {
            if (session.isOpen() && getAddr(session).equals("up")) {
                try {
//                    String msg = "服务器定时推送: " + System.currentTimeMillis();
                    session.getBasicRemote().sendText(msg);
                    log.info("已推送消息给客户端: {}", session.getId());
                } catch (IOException e) {
                    log.error("推送失败: {}", e.getMessage());
                }
            }
        }
    }
    // 获取连接地址
    private String getAddr(Session session){
        String query = session.getQueryString(); // addr=front
        String addr = null;
        if (query != null && query.contains("addr=")) {
            addr = query.split("addr=")[1];
        }
        return addr;
    }
}
